package com.ljx.qqpro.common.exception;

import com.ljx.qqpro.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.M
 * @version 1.0
 * @description
 * @date 2023/2/12 17:01
 */
@Slf4j
//@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {

    //对项目的自定义异常类型进行处理
    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> customException(MyException e) {
        //记录异常
        log.error("系统异常：{}", e.getMessage(), e);
        //解析出异常信息
        String errMessage = e.getMessage();
        return Result.fail(null, errMessage);
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> exception(Exception e) {

        //记录异常
        log.error("系统异常：{}", e.getMessage(), e);

        return Result.fail(null, CommonError.UNKOWN_ERROR.getErrMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> MethodArgumentNotValidException(MethodArgumentNotValidException e) {

        BindingResult bindingResult = e.getBindingResult();
        List<String> errors = new ArrayList<>();
        bindingResult.getFieldErrors().stream().forEach(item -> {
            errors.add(item.getDefaultMessage());
        });
        // 将list转为string拼接起来
        String errMsg = StringUtils.join(errors, ",");
        //记录异常
        log.error("系统异常：{}", e.getMessage(), e);
        //解析出异常信息
        return Result.fail(null, errMsg);
    }


}
